
import org.jsoup.*;
import org.jsoup.Connection.*;
import org.jsoup.nodes.*;
import org.jsoup.select.*;

import java.util.*;

import org.jsoup.Connection.Method;

public class TSquareClassExplorer extends Thread {

	public static Collection<TSquareClassExplorer> allTSquareClasses;
	
	static {
		allTSquareClasses = new HashSet<TSquareClassExplorer>();
	}
	
	private String link;
	private POC facesHandler;
	
	public String getLink() {
		return link;
	}
	
	public void getLink(String newLink) {
		this.link = newLink;
	}
	
	public TSquareClassExplorer(String className, String link, POC facesHandler) {
		super(className);
		this.link = link;
		this.facesHandler = facesHandler;
		
		// Add to the static collection
		allTSquareClasses.add(this);
	}
	
	private Document getDocument(String url, Map<String, String> data) {
		return getDocument(url, data, Method.GET);
	}
	
	private Document getDocument(String url, Map<String, String> data, Method meth) {
		Document doc = null;
		synchronized (facesHandler) {
			try {
				doc = facesHandler.send(link, null, Method.GET, false);				
			} catch (Exception e) {
				System.err.println(getName() + " did not import roster successfully.");
			}
		}
		return doc;
	}
	
	@Override
	public void run() {
		if (link != null) {
			// Get Course page
			Document doc = getDocument(link, null);
			Elements eles = doc.select("a:contains(Roster)");
			if (!eles.isEmpty() && eles.size() == 1) {
				// Get Roster page
				doc = getDocument(eles.get(0).attr("href"), null);
				System.out.println(doc);
				eles = doc.select("iframe");
//				System.out.println(eles);
				if (eles.size() == 1) {
					doc = getDocument(eles.get(0).attr("href"), null);
					eles = doc.select("img");
					print(eles);
					print(" imported roster successfully");
				} else {
					System.err.println(getName() + " does not have pictures available for the roster.");
//					print(doc.select("a"));
				}
			} else
				System.err.println(getName() + " does not have an available class Roster.");
		}
	}
	
	private void print(Object o) {
		if (o != null)
			print(o.toString());
	}
	
	private void print(String print) {
		System.out.println("\n\n[" + getName()+ "] " + link);
		System.out.println("\t" + print);
	}
	
	@Override
	public String toString() {
		return this.getName();
	}
}
